import axios from 'axios'
import router from '../router/index'
import qs from 'qs'
import ElementUI from 'element-ui';
import {debounce} from './func'

let errorMsg=debounce((res)=>{
  ElementUI.Message.error(res.data.msg);
},1000)
// axios 配置
axios.defaults.timeout = 300000//调用接口时间限制
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// axios.defaults.baseURL = '/api'

// POST传参序列化
axios.interceptors.request.use((config) => {
  if(config.url.split('?')[0]!='screenChilds'&&config.url.split('?')[0]!='waybill_allocation_all_start'&&config.url.split('?')[0]!='pdd_orders_pick_up'){
    eventBus.$emit("Loading",true)
  }
  // let token =   window.localStorage.getItem("token")
  // if (!!token) {
    //   config.headers['token'] = token
    // }
    //window.location.reload()  this.$router.go(0)//部署项目强制刷新页面
    return config
  }, (error) => {
    return Promise.reject(error)
  })
  let isOverTime=false;
  // 返回状态判断
axios.interceptors.response.use((res) => {
  var b = res.config.url.indexOf("?", 5);
  if (res.data.code =='004'||res.data.code=='005') {
    if(!isOverTime){
      let lang=!!JSON.parse(localStorage.getItem('language'))?JSON.parse(localStorage.getItem('language')).lang:'zh'
      //退出登录不提示信息
      if(res.config.url.slice(5,b)!='logout'){
        if(lang=='zh'){
          ElementUI.Notification({
            title: '超时提醒',
            message: '登陆超时请重新登录！',
            type: 'warning',
            duration:2000
          });
        }else if(lang=='ru'){
          ElementUI.Notification({
            title: 'Напоминание о тайм-ауте',
            message: 'Время входа в систему истекло, пожалуйста, войдите снова!',
            type: 'warning',
            duration:2000
          });
        }else if(lang=='kz'){
          ElementUI.Notification({
            title: 'Күту туралы еске салғыш',
            message: 'Ұзақ уақыт бойы операция жасамаған болсаңыз, жүйеге қайта кіріңіз!',
            type: 'warning',
            duration:2000
          });
        }else if(lang=='en'){
          ElementUI.Notification({
            title: 'Timeout reminder',
            message: 'Login timeout, please log in again!',
            type: 'warning',
            duration:2000
          });
        }
      }
      isOverTime=true
      router.push({path:"/Login"})
    }
    return Promise.reject(res);
  }else{
    isOverTime=false
  }
  if (res.data.code =='006') {
    location.reload(true)
    // localStorage.clear()
  }
  if (res.data.code =='10003') {
    // 当前页面没有权限403
    router.push({path:"/403"})
  }
  if (res.data.code =='10002') {
    // 当前页面没有权限403
    router.push({path:"/login"})
  }
  if(res.config.url.split('?')[0]!=res.config.baseURL+'/screenChilds'&&res.config.url.split('?')[0]!=res.config.baseURL+'/waybill_allocation_all_start'&&res.config.url.split('?')[0]!=res.config.baseURL+'/pdd_orders_pick_up'){
    eventBus.$emit("Loading",false)
  }
  if(!res.data.success){
    errorMsg(res)
  }
  return res
}, (error) => {
  eventBus.$emit("Loading",false)
  let lang=!!JSON.parse(localStorage.getItem('language'))?JSON.parse(localStorage.getItem('language')).lang:'zh'
      if(lang=='zh'){
      ElementUI.Notification({
        title: '错误提醒',
        message: '无法访问服务器！',
        type: 'warning',
        duration:3000
      });
    }else if(lang=='ru'){
      ElementUI.Notification({
        title: 'Напоминание об ошибке',
        message: 'Невозможно получить доступ к серверу!',
        type: 'warning',
        duration:3000
      });
    }else if(lang=='kz'){
      ElementUI.Notification({
        title: 'Қате туралы еске салғыш',
        message: 'Серверге кіру мүмкін емес!',
        type: 'warning',
        duration:3000
      });
    }else if(lang=='en'){
      ElementUI.Notification({
        title: 'Error Reminder',
        message: 'Can not reach server!',
        type: 'warning',
        duration:3000
      });
    }
  // 404等问题可以在这里处理
  return Promise.reject(error)
})



export function get(url, params,isKz) {
  axios.defaults.responseType= ''
  if(isKz){
    axios.defaults.baseURL = '/api_kz'
  }else{
    axios.defaults.baseURL = '/api'
  }
  let lang=''
  if(!!window.localStorage.getItem('language')){
    lang=JSON.parse(window.localStorage.getItem('language')).lang=='kz'?'kk':JSON.parse(window.localStorage.getItem('language')).lang
  }
  return new Promise((resolve, reject) => {
    axios.get(url+'?EDITION='+ window.localStorage.getItem('EDITION')+'&lang='+ lang+'&token='+ window.localStorage.getItem('token')+'&jurisdiction='+ this.$store.state.tabsId, {
      params: params,
      headers: {
        'SourceDomain': window.location.origin
      }
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      // reject(err.data)
    })
  })
}

export function post(url, params,isKz) {
  if(isKz){
    axios.defaults.baseURL = '/api_kz'
  }else{
    axios.defaults.baseURL = '/api'
  }
  let lang=''
  if(!!window.localStorage.getItem('language')){
    lang=JSON.parse(window.localStorage.getItem('language')).lang=='kz'?'kk':JSON.parse(window.localStorage.getItem('language')).lang
  }
  return new Promise((resolve, reject) => {
    axios.post(url+'?EDITION='+ window.localStorage.getItem('EDITION')+'&lang='+ lang+'&token='+ window.localStorage.getItem('token')+'&jurisdiction='+ this.$store.state.tabsId, qs.stringify(params))
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        // reject(err.data)
      })
  })
}

export function postForm(url, params,isKz) {
  if(isKz){
    axios.defaults.baseURL = '/api_kz'
  }else{
    axios.defaults.baseURL = '/api'
  }
  let lang=''
  if(!!window.localStorage.getItem('language')){
    lang=JSON.parse(window.localStorage.getItem('language')).lang=='kz'?'kk':JSON.parse(window.localStorage.getItem('language')).lang
  }
  return new Promise((resolve, reject) => {
    if(url=="waybill_update_file"){
      axios.post(url+'?EDITION='+ window.localStorage.getItem('EDITION')+'&lang='+ lang+'&token='+ window.localStorage.getItem('token')+'&jurisdiction='+ this.$store.state.tabsId, params, {timeout:500000,"headers": {'Content-Type': 'multipart/form-data;charset=UTF-8'}})
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          // reject(err.data)
        })
    }else{
      axios.post(url+'?EDITION='+ window.localStorage.getItem('EDITION')+'&lang='+ lang+'&token='+ window.localStorage.getItem('token')+'&jurisdiction='+ this.$store.state.tabsId, params, {"headers": {'Content-Type': 'multipart/form-data;charset=UTF-8'}})
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          // reject(err.data)
        })
    }
  })
}

export function updateImg(url, params,isKz) {
  if(isKz){
    axios.defaults.baseURL = '/api_kz'
  }else{
    axios.defaults.baseURL = '/api'
  }
  let lang=''
  if(!!window.localStorage.getItem('language')){
    lang=JSON.parse(window.localStorage.getItem('language')).lang=='kz'?'kk':JSON.parse(window.localStorage.getItem('language')).lang
  }
  return new Promise((resolve, reject) => {
    axios.post(url+'?EDITION='+ window.localStorage.getItem('EDITION')+'&lang='+ lang+'&token='+ window.localStorage.getItem('token')+'&jurisdiction='+  window.localStorage.getItem('tabsCard'), params, {"headers": {'Content-Type': 'multipart/form-data;charset=UTF-8'}})
    .then(res => {
      resolve(res.data)
    })
    .catch(err => {
      // reject(err.data)
    })
  })
}


//通过下载中心后台下载文件
export function downloadCenterLoad(url, params,isKz) {
  axios.defaults.responseType= ''
  if(isKz){
    axios.defaults.baseURL = '/api_kz'
  }else{
    axios.defaults.baseURL = '/api'
  }
  let lang=''
  if(!!window.localStorage.getItem('language')){
    lang=JSON.parse(window.localStorage.getItem('language')).lang=='kz'?'kk':JSON.parse(window.localStorage.getItem('language')).lang
  }
  this.$prompt(this.$t('common.file_name'), this.$t('common.prompt'), {
    confirmButtonText: this.$t('common.confirm'),
    cancelButtonText: this.$t('common.cancel'),
    closeOnClickModal:false,
    inputValue:'File_'+Date.now()
  }).then(({ value }) => {
    params.filename=value
    axios.get(url+'?EDITION='+ window.localStorage.getItem('EDITION')+'&lang='+ lang+'&token='+ window.localStorage.getItem('token')+'&jurisdiction='+ this.$store.state.tabsId, {
      params: params
    }).then(res => {
      if(res.data.success==false){
        this.$message.warning(res.data.msg);
      }else{
        this.$confirm(this.$t('common.downLoad_success_msg'), this.$t('common.prompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
      }).then(() => {
        eventBus.$emit('toDownloadCenter')
      }).catch(() => {});
      }
    }).catch(err => {
      // reject(err.data)
    })
  }).catch(() => {});
}

